package com.yitongmao.fragment;


import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.yitongmao.AppConstancts;
import com.yitongmao.activity.AboutWeActivity;
import com.yitongmao.activity.AddAddressActivity;
import com.yitongmao.activity.ExchangeActivity;
import com.yitongmao.activity.ForgetPassWordActivity;
import com.yitongmao.activity.LoginActivity;
import com.yitongmao.activity.MyAttentionActivity;
import com.yitongmao.activity.MyIndentActivity;
import com.yitongmao.activity.MyPersonaldatailsActivity;
import com.yitongmao.activity.RegisterActivity;
import com.yitongmao.activity.UserSetActivity;
import com.yitongmao.adapter.MyAdapterGridView;
import com.yitongmao.bean.LoginHuancunBean;
import com.yitongmao.bean.UserMessageBean;
import com.yitongmao.common.CallBackListener;
import com.yitongmao.core.cache.ACache;
import com.yitongmao.core.network.service.BaseService;
import com.yitongmao.dialog.CommomDialog;
import com.yitongmao.util.GlideCircleTransform;
import com.yitongmao.util.SignUtil;
import com.yitongmao.util.ToastUtils;
import com.yitongmao.yitmfruit.R;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;

import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * A simple {@link Fragment} subclass.
 */
public class MyFragment extends Fragment {
    public String statenum0 = "0";
    public String statenum1 = "1";
    public String statenum2 = "2";
    public String statenum3 = "3";
    @Bind(R.id.mDaiFuKuan)
    AutoRelativeLayout mDaiFuKuan;
    @Bind(R.id.mDaiFaHuo)
    AutoRelativeLayout mDaiFaHuo;
    @Bind(R.id.mDaiShouHuo)
    AutoRelativeLayout mDaiShouHuo;
    @Bind(R.id.mTuiKuan)
    AutoRelativeLayout mTuiKuan;
    private GridView mMyGridView;
    private ImageView iv_fragment_me_headimg;
    private AutoRelativeLayout mLookIndent;
    private TextView tv_fragment_me_nickname;
    private LoginHuancunBean loginHuancunBean;
    private Object headImage;
    private int loginId1;
    private boolean isComing = true;
    private AutoLinearLayout mLoginZhuce;
    private Button mlogin;
    private Button mZhuCe;
    private String  number = "4000114888";
    private static final int WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 104;
    public MyFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my, container, false);
        Gson gson = new Gson();
        String loginId = ACache.get(getActivity()).getAsString("loginId");
        if (loginId != null) {
            loginHuancunBean = gson.fromJson(loginId, LoginHuancunBean.class);
        }
        initView(view);
        setData();
        setOnClick();
        onViewClicked(view);
        ButterKnife.bind(this, view);
        return view;
    }

    private void setOnClick() {
        iv_fragment_me_headimg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (loginHuancunBean != null) {
                    Intent intent = new Intent(getActivity(), MyPersonaldatailsActivity.class);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.slide_bottom_in, R.anim.slide_bottom_out);
                } else {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.slide_bottom_in, R.anim.slide_bottom_out);
                }
            }
        });
        mMyGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                gridviewOnclick(position);
            }
        });
        mLookIndent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (loginHuancunBean != null) {
                    Intent intent = new Intent(getActivity(), MyIndentActivity.class);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.slide_bottom_in, R.anim.slide_bottom_out);
                }
            }
        });
        //登录
        mlogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.slide_bottom_in, R.anim.slide_bottom_out);
            }
        });
        //注册
        mZhuCe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), RegisterActivity.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.slide_bottom_in, R.anim.slide_bottom_out);
            }
        });
    }
    public void gridviewOnclick(int position) {
        switch (position) {
            case 0://我的关注
                if (loginHuancunBean != null) {
                    Intent intent = new Intent(getActivity(), MyAttentionActivity.class);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.slide_bottom_in, R.anim.slide_bottom_out);
                }
                break;
            case 1://修改密码
                if (loginHuancunBean != null) {
                    Intent intent = new Intent(getActivity(), ForgetPassWordActivity.class);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.slide_bottom_in, R.anim.slide_bottom_out);
                }
                break;
            case 2://收货信息
                if (loginHuancunBean != null) {
                    Intent intent = new Intent(getActivity(), AddAddressActivity.class);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.slide_bottom_in, R.anim.slide_bottom_out);
                }
                break;
            case 3://关于我们
                Intent intent = new Intent(getActivity(), AboutWeActivity.class);
                startActivity(intent);
                break;
            case 4://联系我们
                //权限判断
                if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CALL_PHONE)
                        != PackageManager.PERMISSION_GRANTED) {
                    //申请WRITE_EXTERNAL_STORAGE权限
                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CALL_PHONE},
                            WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
                } else {
                    new CommomDialog(getActivity(), R.style.dialog, " ", new CommomDialog.OnCloseListener() {
                        @Override
                        public void onClick(Dialog dialog, boolean confirm) {
                            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+number));
                            startActivity(intent);
                        }
                    }).setTitle("是否拨打400-011-4888？").show();
                }
                break;
            case 5://用户设置
                if (loginHuancunBean != null) {
                    intent = new Intent(getActivity(), UserSetActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.slide_bottom_in, R.anim.slide_bottom_out);
                }
                break;
        }

    }

    public void initView(View view) {
        mlogin = (Button) view.findViewById(R.id.mlogin);
        mZhuCe = (Button) view.findViewById(R.id.mZhuCe);
        mLoginZhuce = (AutoLinearLayout) view.findViewById(R.id.mLoginZhuce);
        mMyGridView = (GridView) view.findViewById(R.id.mMyGridView);
        iv_fragment_me_headimg = (ImageView) view.findViewById(R.id.iv_fragment_me_headimg);
        mLookIndent = (AutoRelativeLayout) view.findViewById(R.id.mLookIndent);
        tv_fragment_me_nickname = (TextView) view.findViewById(R.id.tv_fragment_me_nickname);
        Gson gson = new Gson();
        String loginId = ACache.get(getActivity()).getAsString("loginId");
        if (loginId != null) {
            loginHuancunBean = gson.fromJson(loginId, LoginHuancunBean.class);
            loginId1 = loginHuancunBean.userInfo.loginId;
            userMessage(String.valueOf(loginHuancunBean.userInfo.id));
        } else {
            mLoginZhuce.setVisibility(View.VISIBLE);
        }
    }

    //得到用户信息并展示
    public void userMessage(String userId) {
        Map params = new TreeMap();
        String timestamp = String.valueOf(System.currentTimeMillis());
        String nonce = String.valueOf(new Random().nextInt());
        params.put("userId", userId);
        params.put("timestamp", timestamp);
        params.put("nonce", nonce);
        params.put("signLogin", SignUtil.signLogin(nonce, timestamp));
        params.put("loginId", String.valueOf(loginId1));
        params.put("sign", SignUtil.sign(params)); //这里也需要时完整的url
        BaseService.getInstance().simplePostRequest(AppConstancts.Net.userMessageUrl, params, new CallBackListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(Object result) {
                //Log.e("zzz", "user:" + result);
                String string = (String) result;
                Gson gson = new Gson();
                UserMessageBean userMessageBean = gson.fromJson(string, UserMessageBean.class);
                Log.e("zzz", "" + userMessageBean.toString());
                if (userMessageBean.result.state.equals("1")) {
                    if (userMessageBean.user.headImage != null) {
                        Glide.with(getActivity()).load(userMessageBean.user.headImage).transform(new GlideCircleTransform(getActivity())).into(iv_fragment_me_headimg);
                    }
                    tv_fragment_me_nickname.setVisibility(View.VISIBLE);
                    tv_fragment_me_nickname.setText(String.valueOf(userMessageBean.user.petName));
                }
            }

            @Override
            public void onFail(Object result) {
                ToastUtils.showShort(getActivity(), "失败");
            }
        });
    }

    public void setData() {
        mMyGridView.setAdapter(new MyAdapterGridView(getActivity()));
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.mDaiFuKuan, R.id.mDaiFaHuo, R.id.mDaiShouHuo, R.id.mTuiKuan})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.mDaiFuKuan:
                if (loginHuancunBean != null) {
                    Intent intent0 = new Intent(getActivity(), MyIndentActivity.class);
                    intent0.putExtra("one", statenum0);
                    startActivity(intent0);
                } else {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.slide_bottom_in, R.anim.slide_bottom_out);
                }
                break;
            case R.id.mDaiFaHuo:
                if (loginHuancunBean != null) {
                    Intent intent1 = new Intent(getActivity(), MyIndentActivity.class);
                    intent1.putExtra("two", statenum1);
                    startActivity(intent1);
                } else {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.slide_bottom_in, R.anim.slide_bottom_out);
                }
                break;
            case R.id.mDaiShouHuo:
                if (loginHuancunBean != null) {
                    Intent intent2 = new Intent(getActivity(), MyIndentActivity.class);
                    intent2.putExtra("three", statenum2);
                    startActivity(intent2);
                } else {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.slide_bottom_in, R.anim.slide_bottom_out);
                }
                break;
            case R.id.mTuiKuan:
                if (loginHuancunBean != null) {
                    Intent intent3 = new Intent(getActivity(), ExchangeActivity.class);
                    startActivity(intent3);
                } else {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.slide_bottom_in, R.anim.slide_bottom_out);
                }
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isComing) return;
        try {
            if (!String.valueOf(loginHuancunBean.userInfo.id).equals("")) {
                userMessage(String.valueOf(loginHuancunBean.userInfo.id));
            }
        } catch (Exception e) {
            Log.e("zzz", "" + e);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        isComing = false;
    }
}
